//package com.xhsj.user.flowable.web;
//
//import com.xhsj.user.flowable.service.FlowableService;
//import com.xhsj.user.flowable.vo.FlowableCallableVo;
//import com.xhsj.user.flowable.vo.FlowableTask;
//import com.xhsj.user.utils.Message;
//import com.xhsj.user.utils.StringUtils;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.io.IOUtils;
//import org.flowable.bpmn.model.BpmnModel;
//import org.flowable.bpmn.model.FlowNode;
//import org.flowable.bpmn.model.SequenceFlow;
//import org.flowable.engine.*;
//import org.flowable.engine.history.HistoricActivityInstance;
//import org.flowable.engine.history.HistoricProcessInstance;
//import org.flowable.engine.repository.Deployment;
//import org.flowable.engine.repository.DeploymentBuilder;
//import org.flowable.engine.runtime.Execution;
//import org.flowable.engine.runtime.ProcessInstance;
//import org.flowable.image.ProcessDiagramGenerator;
//import org.flowable.task.api.Task;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.CollectionUtils;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.*;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//
///**
// * @Description FlowableController
// * @Author suxiaolin
// * @Date 2020/12/31 16:41
// */
//@Slf4j
//@RestController
//@RequestMapping("/flowable")
//public class FlowableController {
//    @Autowired
//    private RuntimeService runtimeService;
//    @Autowired
//    private TaskService taskService;
//    @Autowired
//    private RepositoryService repositoryService;
//    @Autowired
//    private ProcessEngine processEngine;
//
//    @Autowired
//    private FlowableService flowableService;
//
//    @Autowired
//    private HistoryService historyService;
//
//    /**
//     * 启动流程
//     *
//     * @author 苏小林
//     * @date 2020/12/31 16:50
//     * @return: com.xhsj.user.utils.Message
//     */
//    @RequestMapping(value = "/startProcess", method = RequestMethod.GET)
//    @Transactional(rollbackFor = Exception.class)
//    public Message startProcess() throws Exception {
//
//        //启动流程
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("zhuguan", "289");
//        String businessKey = "123456";
//        // 业务表添加流程实例id
//        final String[] processInstanceId = {""};
//
//        flowableService.startProcess(businessKey, map, "leave_apply", (instanceId) -> {
//            System.err.println("进入修改实例id：" + instanceId);
////            processInstanceId[0] = String.valueOf(instanceId.get("processInstanceId"));
//            // TODO: 2021/1/4 修改业务数据
//
//        });
//
//        return Message.success("成功", processInstanceId[0]);
//
//    }
//
//
//    /**
//     * 查询待办列表
//     */
//    @RequestMapping(value = "/list", method = RequestMethod.GET)
//    public Object list(String userId) {
//        List<FlowableTask> leave_apply = flowableService.todoList(userId, "leave_apply");
//        // TODO: 2021/1/4 根据业务id查询数据
//
//        return leave_apply;
//    }
//
//    /**
//     * 查询待办列表
//     */
//    @RequestMapping(value = "/hisTask", method = RequestMethod.GET)
//    public Object hisTask(String userId) {
//        flowableService.hisTask(userId, "leave_apply");
//        // TODO: 2021/1/4 根据业务id查询数据
//
//        return null;
//    }
//
//
//    /**
//     * 流程部署
//     */
//    @RequestMapping(value = "/deployFlow", method = RequestMethod.GET)
//    public String deployFlow() {
//        String filePath = "processes/leave-apply.bpmn20.xml";
//        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment()
//                .addClasspathResource(filePath);
//        Deployment deployment = deploymentBuilder.deploy();
//        log.info("成功：部署工作流成：" + filePath);
//        log.info("部署ID："+deployment.getId());
//        log.info("部署时间："+deployment.getDeploymentTime());
//        return deployment.getId();
//    }
//
//
//    @GetMapping("/handleAudit")
//    public void handleAudit(@RequestParam("taskId") String taskId) throws Exception {
//        //通过审核
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("flowCode", 0);
//        map.put("remarks", "123456789");
//
//        flowableService.handleAudit(taskId, map, (map1 -> {
//
//        }));
//    }
//
////    @GetMapping("/generateDiagram")
////    public ResponseEntity<byte[]> generateDiagram(HttpServletResponse httpServletResponse, @RequestParam("processInstanceId") String processInstanceId) throws Exception {
////
////        try {
////            // 获取历史流程实例
////            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
////            // 获取流程中已经执行的节点，按照执行先后顺序排序
////            List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceId().asc().list();
////            // 构造已执行的节点ID集合
////            List<String> executedActivityIdList = new ArrayList<String>();
////            for (HistoricActivityInstance activityInstance : historicActivityInstanceList) {
////                executedActivityIdList.add(activityInstance.getActivityId());
////            }
////            // 获取bpmnModel
////            BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
////            // 获取流程已发生流转的线ID集合
////            List<String> flowIds = this.getExecutedFlows(bpmnModel, historicActivityInstanceList);
////            ProcessEngineConfiguration processEngineConfig = processEngine.getProcessEngineConfiguration();
////            // 使用默认配置获得流程图表生成器，并生成追踪图片字符流
////            ProcessDiagramGenerator processDiagramGenerator = processEngine.getProcessEngineConfiguration().getProcessDiagramGenerator();
////            //你也可以 new 一个
////            //DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator;
////            InputStream in = processDiagramGenerator.generateDiagram(bpmnModel, "bmp", executedActivityIdList, flowIds,processEngineConfig.getActivityFontName(),processEngineConfig.getLabelFontName(), processEngineConfig.getAnnotationFontName(), processEngineConfig.getClassLoader(), 1.0,false);
////            byte[] buffer = null;
////            try {
////                ByteArrayOutputStream bos = new ByteArrayOutputStream();
////                byte[] b = new byte[1024];
////                int n;
////                while ((n = in.read(b)) != -1) {
////                    bos.write(b, 0, n);
////                }
////                in.close();
////                bos.close();
////                buffer = bos.toByteArray();
////            } catch (Exception e) {
////                e.printStackTrace();
////            }
////
////            HttpHeaders headers = new HttpHeaders();
////            HttpStatus statusCode = HttpStatus.OK;
////            headers.add("Content-Type", "image/png");
////            headers.add("Content-Disposition",
////                    String.format("inline; filename=\"%s\"", java.net.URLEncoder.encode("2.png", "UTF-8")));
////
////            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(buffer, headers, statusCode);
////            return entity;
////        } catch (Exception e) {
////            e.printStackTrace();
////            return null;
////        }
////
////
////    }
//
////    public InputStream getResourceDiagramInputStream(String id) {
////        try {
////        // 获取历史流程实例
////            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(id).singleResult();
////            // 获取流程中已经执行的节点，按照执行先后顺序排序
////            List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery().processInstanceId(id).orderByHistoricActivityInstanceId().asc().list();
////            // 构造已执行的节点ID集合
////            List<String> executedActivityIdList = new ArrayList<String>();
////            for (HistoricActivityInstance activityInstance : historicActivityInstanceList) {
////                executedActivityIdList.add(activityInstance.getActivityId());
////            }
////            // 获取bpmnModel
////            BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
////            // 获取流程已发生流转的线ID集合
////            List<String> flowIds = this.getExecutedFlows(bpmnModel, historicActivityInstanceList);
////            // 使用默认配置获得流程图表生成器，并生成追踪图片字符流
////            ProcessDiagramGenerator processDiagramGenerator = processEngine.getProcessEngineConfiguration().getProcessDiagramGenerator();
////            //你也可以 new 一个
////            //DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator;
////            InputStream in = processDiagramGenerator.generateDiagram(bpmnModel, "png", executedActivityIdList, flowIds, "宋体", "微软雅黑", "黑体", null, 2.0,false);
////            byte[] buffer = null;
////            try {
////                ByteArrayOutputStream bos = new ByteArrayOutputStream();
////                byte[] b = new byte[1024];
////                int n;
////                while ((n = in.read(b)) != -1) {
////                    bos.write(b, 0, n);
////                }
////                in.close();
////                bos.close();
////                buffer = bos.toByteArray();
////            } catch (Exception e) {
////                e.printStackTrace();
////            }
////
////            HttpHeaders headers = new HttpHeaders();
////            HttpStatus statusCode = HttpStatus.OK;
////            headers.add("Content-Type", "image/png");
////            headers.add("Content-Disposition",
////                    String.format("inline; filename=\"%s\"", java.net.URLEncoder.encode("1.png", "UTF-8")));
////
////            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(buffer, headers, statusCode);
////            return null;
////        } catch (Exception e) {
////            e.printStackTrace();
////            return null;
////        }
////    }
//
//    private List<String> getExecutedFlows(BpmnModel bpmnModel,
//                                          List<HistoricActivityInstance> historicActivityInstanceList) {
//        List<String> executedFlowIdList = new ArrayList<>();
//        for (int i = 0; i < historicActivityInstanceList.size() - 1; i++) {
//            HistoricActivityInstance hai = historicActivityInstanceList.get(i);
//            FlowNode flowNode = (FlowNode) bpmnModel.getFlowElement(hai.getActivityId());
//            List<SequenceFlow> sequenceFlows = flowNode.getOutgoingFlows();
//            if (sequenceFlows.size() > 1) {
//                HistoricActivityInstance nextHai = historicActivityInstanceList.get(i + 1);
//                sequenceFlows.forEach(sequenceFlow -> {
//                    if (sequenceFlow.getTargetFlowElement().getId().equals(nextHai.getActivityId())) {
//                        executedFlowIdList.add(sequenceFlow.getId());
//                    }
//                });
//            } else if (sequenceFlows.size() == 1) {
//                executedFlowIdList.add(sequenceFlows.get(0).getId());
//            }
//
//        }
//        return executedFlowIdList;
//    }
//}
